package com.star.io.netty.socket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.nio.charset.StandardCharsets;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {  
    private int length; // 消息长度（包括消息头和消息体）  
    private byte type;  // 消息类型（这里简单用一个字节表示）  
    private String content; // 消息内容  
  
    // 构造函数、getter 和 setter 方法省略  

    public Message(byte type, String content) {
        this.type = type;
        this.content = content;
    }

    @Override
    public String toString() {  
        return "Message{" +  
                "length=" + length +  
                ", type=" + type +  
                ", content='" + content + '\'' +  
                '}';  
    }  
  
    // 将 Message 编码为 ByteBuf(fer)
    public ByteBuf encode(ByteBufAllocator alloc) {
        byte[] contentBytes = content.getBytes(StandardCharsets.UTF_16);
        int totalLength = 4 + 1 + contentBytes.length; // 4(length) + 1(type) + content.length  
  
        ByteBuf buf = alloc.buffer(totalLength);  
        buf.writeInt(totalLength); // 写入消息长度  
        buf.writeByte(type);       // 写入消息类型  
        buf.writeBytes(contentBytes); // 写入消息内容  
  
        return buf;  
    }  
  
    // 从 ByteBuf 解码为 Message  
    public static Message decode(ByteBuf buf) {  
        int length = buf.readInt();  
        byte type = buf.readByte();  
        byte[] contentBytes = new byte[length - 5]; // 5 = 4(length) + 1(type)  
        buf.readBytes(contentBytes);  
  
        String content = new String(contentBytes, StandardCharsets.UTF_16);
        return new Message(length, type, content);
    }  
}